package bcxd.firstline.credit.machining;

import java.sql.Connection;

import jt.classic.system.context.ISystemContext;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;

import org.limp.basework.MachiningException;
import org.limp.basework.SimpleBean;
import org.limp.basework.SimpleBean4Table;
import org.limp.basework.SimpleBeanMachining;
import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;

import bcxd.firstline.user.manager.AppUserManager;

/**
 * 信用机构入驻信息维护
 * 
 * @author mido
 * 
 */
public class CreditApplyMachining implements SimpleBeanMachining {

	public SimpleBean machining(SimpleBean bean, Table table,
			CommonBean4HSQ cbh, Connection conn, int type)
			throws MachiningException {
		// TODO Auto-generated method stub
		if (type == -4) {
			// bean.getResource().put("cr_status", "0");
		} else if (type == 3) {
			if (ISystemContext.invalidSesstion(cbh.getRequest())) {
				throw new MachiningException("invalid session.");
			}
			// 更新会话用户对象信息
			IUser user = ISystemContext.getSessionUser(cbh.getRequest());

			SimpleBean4Table userBean = new SimpleBean4TableImpl("bcxduser");

			userBean.getResource().put("uid", user.id());
			userBean.getResource()
					.put("uname", cbh.getResource().get("cr_name"));
			userBean.getResource().put("ustatus", "1");

			BaseworkUtil util = new BaseworkUtil();
			try {
				util.manualUpdate1(userBean, conn);
			} catch (Exception ex) {
				throw new MachiningException("update application-user error.",
						ex);
			}

		} else if (type == 4000) {
			// 入驻资料更新成功,重置会话
			IUser user = ISystemContext.getSessionUser(cbh.getRequest());
			// 首次入驻更新资料信息,更新后重置会话
			if (user.iflag() == 0) {
				Connection newConn = null;
				try {
					SystemDataSource ds = SystemDataSource.getInstance();
					newConn = ds.getConnection();

					AppUserManager manager = new AppUserManager(newConn);

					IUser appUser = manager.getBcxdUserById(user.id());

					ISystemContext.resetSessionUser(cbh.getRequest(), appUser);
				} catch (Exception ex) {
					SystemDataSource.rollbackConnection(newConn);
					throw new MachiningException("get application-user error.",
							ex);
				} finally {
					SystemDataSource.closeConnection(newConn);
				}
			}
		}
		return null;
	}

}
